const app = getApp();
import {
  login, userUpdate,
} from "../utils/request/api";
import msg from "../utils/msg";

export default class User {
  GF_ACCOUNT = '' as string;
	GF_ID = 0 as number | string;
  name = '' as string;
  phone= '' as string;
  openid = '' as string;
  is_merchant = false as boolean;//是否绑定商家账号
  club_code = "" as string;
  club_id = "" as string;
  club_name = "" as string;
  apply_id = "" as string;
  head_pic = "" as string;
  sex = "" as string;
  AccessKey={
    AccessKeyId:'' as string,
    AccessKeySecret:'' as string,
  }
	constructor(checkLogin:boolean=false) {
    this.dataInit();
    if(checkLogin){
      this.checkLogin(1);
    }
	};
	Login =  (phone_code:string="",navigateBack:boolean=true) => {
    let self = this;
    if(!phone_code) phone_code="";
    return new Promise(async(resolve,reject)=>{
      //获取电话号码
    await wx.login({
      success: async function (res) {
        if (res.code) {
          //发起网络请求
          //登录
          await login({code:res.code, phone_code:phone_code})
            .then((res:any) => {
              console.log('login_then',res);
              self.setAtt(res.data.data);
              if (!self.openid) {
                msg.show('登录失败', '请重试');
                self.logout();
                return;
              }
              console.log('isLogin');
              app.globalData.isLogin = true;
              self.setStorage();
              if(navigateBack)
                wx.navigateBack();
            })
            .catch((err)=>{
                console.log('login_catch');
                msg.show('登录失败','请检查网络或稍后重试');
                self.logout();
            })
            ;
          msg.hideLoading();
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
      resolve('');
    })
  }
  logout = function () {
    wx.removeStorageSync('user');
  };
	public setAtt(data: any) {
		if(data.GF_ID){this.GF_ID = data.GF_ID;}
		if(data.openid){this.openid = data.openid;}
		if(data.GF_ACCOUNT)this.GF_ACCOUNT = data.GF_ACCOUNT;
    if(data.phone)this.phone = data.phone;
    if(data.apply_id) this.apply_id=data.apply_id;
    if(data.name) this.name=data.name;
    if(data.head_pic) this.head_pic=data.head_pic;
    //商户
    if(data.club_id) this.club_id=data.club_id;
    if(data.club_name) this.club_name=data.club_name;
    if(data.AccessKey) this.AccessKey=data.AccessKey;
	}

	//设置全局变量
	public setStorage() {
		wx.setStorageSync('user', this);
	};
  //检查是否已登录
  //在跳转到一个新的页面后，如果必须登录才能访问，那么取消跳转登录页面会自动回退一个页面
	public checkLogin(param: number = 0): boolean {
		//console.log('user=',user_temp);
		//未登录
		if (this.GF_ID == undefined || this.GF_ID == 0 ) {
			if (param != 0) {
				msg.confirm('您尚未登录', '是否进行一键登陆/注册')
					.then(() => {
						wx.navigateTo({
							url: "/pages/user/login/login",
						})
          })
          .catch(()=>{//取消跳转登录页面,自动回退一个页面
            wx.navigateBack();
          })
			}
			return false;
		}
		//已经登陆
		else {
			return true;
		}
  };
  //检查是否为商户
  public checkMerchant(){
    return this.club_id?true:false;
  };
	//登出
	public logOut(): void {
		console.log('logout!');
    wx.removeStorageSync('user');
    this.dataInit();
	};
	public dataInit(): void {
		let user_temp: User = wx.getStorageSync('user');
		console.log('datainit=',user_temp);
		this.setAtt(user_temp);
  };
  public update(){
    return new Promise((resolve,reject)=>{
      if(!this.checkLogin()) return;
    msg.Loading('更新用户信息');
    userUpdate({openid:this.openid,name:this.name,head_pic:this.head_pic,GF_ID:this.GF_ID,sex:this.sex,GF_account:this.GF_ACCOUNT})
    .then((res)=>{
      msg.hideLoading();
      resolve('');
    });
    })
  };
}